package com.atguigu.srb.sms.controller.api;

import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.utils.RandomUtils;
import com.atguigu.srb.common.utils.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
//@CrossOrigin //跨域
@Slf4j
public class ApiSmsController {

    @Resource
    private SmsService smsService;
    @Resource
    private CoreUserInfoClient coreUserInfoClient;

    @Resource
    private RedisTemplate redisTemplate;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(
            @ApiParam(value = "手机号", required = true)
            @PathVariable String mobile) {
        boolean b1 = coreUserInfoClient.checkMobile(mobile);
        Assert.isTrue(b1 == false, ResponseEnum.MOBILE_EXIST_ERROR);
        boolean b = RegexValidateUtils.checkCellphone(mobile);
        if (b){
            String sixBitRandom = RandomUtils.getSixBitRandom();
            String[] data ={sixBitRandom,"5"};
//            smsService.send(mobile, SmsProperties.TEMPLATE_ID,data);
            redisTemplate.opsForValue().set("srb:sms:code:"+mobile,sixBitRandom,5, TimeUnit.MINUTES);
            return R.ok().Message("短信发送成功");
        }else {
            return R.error().Message("短信发送错误");
        }

    }
    }
